/*
 * by cansik / Florian
 * Datum: 19.08.2010
 * Zeit: 12:38
 * 
 */
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Linq;

using HtmlAgilityPack;

namespace TM.Unofficial.PersonalMessageSystem
{
	/// <summary>
	/// Briefli System in thats-me
	/// </summary>
	public class PMInterface
	{
		Unofficial.Network.VBrowser browser;
		
		/// <summary>
		/// Creates a new PMInterface (inbox and sender)
		/// </summary>
		/// <param name="browser"></param>
		public PMInterface(Unofficial.Network.VBrowser browser)
		{
			//init vars
			this.browser = browser;
		}
		
		/// <summary>
		/// Send a Private Message
		/// </summary>
		/// <param name="pm"></param>
		/// <returns>success</returns>
		public bool SendPM(PersonalMessage pm)
		{
			//Try to send the message
			string xmlresult = browser.PostRequest(new Uri("http://thats-me.ch/ajax.php"), Encoding.UTF8.GetBytes("w=sendpn&betreff=" + pm.Subject + "&an=" + pm.Recipient + "&text=" + pm.Text), false);
			
			//parse result
			XmlDocument xmldoc = new XmlDocument();
			xmldoc.LoadXml(xmlresult);
			
			XmlNode errortag = xmldoc.GetElementsByTagName("error")[0];
			
			if (errortag.InnerText == string.Empty)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		
		/// <summary>
		/// Returns an array of all messages on the page
		/// </summary>
		/// <param name="pagenumber">Page Number of the inbox (1 = first)</param>
		/// <param name="filter">"unread" = All unreaded messages
		/// "unrep" = All unreplied messages
		/// "rep" = All replied messages
		/// "mark" = All favorited messages</param>
		/// <param name="query"></param>
		/// <returns>Array of messages</returns>
		public ReceivedMessage[] GetMessages(int pagenumber, string filter, string query)
		{
			//fetch inbox messages
			List<ReceivedMessage> messages = new List<ReceivedMessage>();
			HtmlDocument doc = new HtmlDocument();
			doc.LoadHtml(browser.GetRequest(new Uri("http://thats-me.ch/tm-briefli/index.php?q=" + query + "&filter=" + filter + "&s=" + pagenumber.ToString()), false));
			
			//Read Nodes by Linq
			List<HtmlNode> messagenodes = (from HtmlNode node in doc.DocumentNode.SelectNodes("//tr")
			                               where node.Id.StartsWith("pn")
			                               select node).ToList();
			
			foreach(HtmlNode mnode in messagenodes)
			{
				messages.Add(FillMessage(mnode));
			}
			
			return messages.ToArray();
		}
		
				/// <summary>
		/// Returns an array of all alerts on the page
		/// </summary>
		/// <param name="pagenumber">Page Number of the inbox (1 = first)</param>
		/// <param name="filter">"unread" = All unreaded alerts
		/// "unrep" = All unreplied alerts
		/// "rep" = All replied alerts
		/// "mark" = All favorited alerts</param>
		/// <param name="query"></param>
		/// <returns>Array of alerts</returns>
		public ReceivedMessage[] GetAlerts(int pagenumber, string filter, string query)
		{
			//fetch inbox alerts
			List<ReceivedMessage> messages = new List<ReceivedMessage>();
			HtmlDocument doc = new HtmlDocument();
			doc.LoadHtml(browser.GetRequest(new Uri("http://thats-me.ch/tm-briefli/benachrichtigungen.php?q=" + query + "&filter=" + filter + "&s=" + pagenumber.ToString()), false));
			
			//Read Nodes by Linq
			List<HtmlNode> alertnodes = (from HtmlNode node in doc.DocumentNode.SelectNodes("//tr")
			                               where node.Id.StartsWith("pn")
			                               select node).ToList();
			
			foreach(HtmlNode anode in alertnodes)
			{
				messages.Add(FillMessage(anode));
			}
			
			return messages.ToArray();
		}
		
		/// <summary>
		/// Fill a Message
		/// </summary>
		/// <param name="mnode">tr Node of the Message</param>
		/// <returns>Recieved Message</returns>
		private ReceivedMessage FillMessage(HtmlNode mnode)
		{
			//Add Message
				ReceivedMessage rm = new ReceivedMessage();
				rm.ID = mnode.Id.Remove(0, 2);
				rm.Sender = mnode.ChildNodes[7].InnerText;
				rm.Date = DateTime.Parse(mnode.ChildNodes[9].InnerText);
				rm.Subject = mnode.ChildNodes[3].InnerText;
				
				//catch status
				string iconname = mnode.ChildNodes[3].FirstChild.Attributes["class"].Value;
				
				switch (iconname) {
					case "ico i-unreplied drin iload":
						rm.Status = PersonalMessageStatus.Unreplied;
						break;
					case "ico i-replied drin iload":
						rm.Status = PersonalMessageStatus.Replied;
						break;
					case "ico i-attention drin iload":
						rm.Status = PersonalMessageStatus.Unreplied;
						rm.Favorite = true;
						break;
					case "ico i-unread drin iload":
						rm.Status = PersonalMessageStatus.Unread;
						//Remove (neu)
						rm.Subject = rm.Subject.Remove(0, 6);
						break;
				}
				
				rm.browser = this.browser;
				
				return rm;
		}
	}
}
